/**
 * Project Name:javaBaseReview
 * Package Name:com.xuwei.base.thread
 * author:David
 * Date:2015年8月19日上午8:33:21
 * Copyright (c) 2015, xw123box@126.com All Rights Reserved.
 *
 */
package com.xuwei.base.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * java5的线程锁技术
 * @author David
 * @since 2015年8月19日 上午8:33:21
 * @version 
 * @since JDK 1.6
 */
public class ThreadLock {
	
	public static void main(String[] args) {
		new ThreadLock().init();
	}
	
	private void init(){
		final Outputer outputer=new Outputer();
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(true){
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					outputer.output("David Xu");
				}
			}
		}).start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(true){
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
//					outputer.output2("Jack D");
					outputer.output3("Jack D");
				}
			}
		}).start();
		
	}
	
	static class Outputer{
		Lock lock=new ReentrantLock();
		public void output(String name){
			int len=name.length();
			lock.lock();
			try{
				for(int i=0;i<len;i++){
					System.out.print(name.charAt(i)); 
				}
				System.out.println();
			}finally{
				lock.unlock();
			}
		}
		
		public synchronized void output2(String name){
			int len=name.length();
				for(int i=0;i<len;i++){
					System.out.print(name.charAt(i)); 
				}
				System.out.println();
		}
		
		public static synchronized void output3(String name){
			int len=name.length();
			for(int i=0;i<len;i++){
				System.out.print(name.charAt(i)); 
			}
			System.out.println();
		}
	}
}

